<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="left">
        <image src="@/static/返回箭头.png" class="back-icon" @tap="goBack"></image>
        <text class="progress">{{ currentIndex + 1 }}/{{ totalWords }}</text>
      </view>
      <view class="stats">
        <view class="lives">
          <text class="heart" v-for="i in maxLives" :key="i" :class="{ 'lost': i > lives }">❤️</text>
        </view>
        <view class="xp-score">
          <view class="score">
            <text class="score-label">分数</text>
            <text class="score-value">{{ score }}</text>
          </view>
          <view class="xp">
            <text class="xp-label">XP</text>
            <text class="xp-value">+{{ xpGained }}</text>
          </view>
        </view>
      </view>
      <!-- 添加倒计时显示 -->
      <view class="countdown">
        <text class="time">{{ formatTime(remainingTime) }}</text>
      </view>
    </view>

    <!-- 单词卡片 -->
    <view class="word-section">
      <text class="word">{{ currentWord.word }}</text>
      <view class="phonetic" @tap="playPronunciation">
        <view class="radio">
          <text class="region">{{ isAmericanAccent ? "美" : "英" }}</text>
          <text class="speaker">
            <image src="@/static/声音.png" class="audio-icon"></image>
          </text>
        </view>
        <text class="symbol">/{{ currentWord.phonetic }}/</text>
      </view>
      <text class="tip">仔细阅读选项，选择正确的释义</text>
    </view>

    <!-- 选项列表 -->
    <view class="options">
      <view
          class="definition-item"
          v-for="(option, index) in currentWord.options"
          :key="index"
          @tap="selectOption(index)"
      >
        <text class="pos">{{ option.pos || '' }}</text>
        <text class="meaning">{{ option.meaning }}</text>
      </view>
    </view>

    <!-- 底部按钮 - 用于跳过当前单词 -->
    <view class="bottom-button" @tap="skipWord">
      <text>跳过此题</text>
    </view>
  </view>
</template>

<script>
import {api} from '@/utils/request.js'

export default {
  data() {
    return {
      currentWord: {
        word: '',
        phonetic: '',
        options: []
      },
      isAmericanAccent: true,
      lives: 5,
      maxLives: 0,
      score: 0,
      xpGained: 0,
      selectedIndex: -1,
      currentIndex: 0,
      totalWords: 10,
      startTime: null,
      learnedWords: [],
      audioContext: null,
      socketTask: null,
      // 修改数据属性
      remainingTime: 0,
      timer: null,
      correctAnswers: 0, // 正确答案计数
      userLevel: 1,
      baseTime: 270,
      timePerLevel: 30,
      challengeStarted: false, // 标记挑战是否已开始
    }
  },
  onLoad(options) {
    uni.$on('triggerToggleAnswer', () => {
      this.loadNextWord()
    })
    // 记录开始时间
    this.startTime = new Date()

    // 初始化已学习单词数组
    this.learnedWords = []

    // 加载第一个单词
    this.loadNextWord()
    this.getUserLevel()
    this.connectWebSocket();
    this.initializeChallenge();
  },
  onUnload() {
    this.closeWebSocket()
    clearInterval(this.timer)
    // 只有在挑战完成或失败时才清除本地存储
    // 这样在正常退出时不会清除进度
  },
  methods: {
    async getUserLevel() {
      const res = await api.getLevel()
      if (res.code === 200) {
        this.score = res.result.point
        this.xpGained = res.result.levelExp
        this.maxLives = res.result.hp
      }
    },
    goBack() {
      uni.switchTab({url: '/pages/learn-mode/learn-mode'})
    },
    async loadNextWord() {
      try {
        uni.showLoading({title: '加载中...'})

        // 从API获取单词数据
        const type = uni.getStorageSync('selectedBookType') || 'cet6'
        const res = await api.getWord(type)

        uni.hideLoading()

        if (res.code === 200 && res.result) {
          // 处理正确选项
          let correctPos = ""
          let correctMeaning = ""
          const pos = res.result.meaning[0].pos
          correctPos = pos
          correctMeaning = res.result.meaning[0]?.tranCn

          const options = [
            {
              pos: correctPos,
              meaning: correctMeaning,
              isCorrect: true
            }
          ]

          // 处理错误选项
          res.result.errorWord?.forEach(item => {
            let errorPos = ""
            let errorMeaning = ""
            const pos = item[0]?.pos
            errorPos = pos
            errorMeaning = item[0]?.tranCn
            options.push({
              pos: errorPos,
              meaning: errorMeaning,
              isCorrect: false
            })
          })

          // 打乱选项顺序
          const shuffledOptions = [...options]
          for (let i = shuffledOptions.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1))
            ;[shuffledOptions[i], shuffledOptions[j]] = [shuffledOptions[j], shuffledOptions[i]]
          }

          // 设置当前单词
          this.currentWord = {
            word: res.result.handWord,
            correctId: res.result.id,
            options: shuffledOptions,
            phrases: res.result.phrases,
            examples: res.result.sentences,
            book: res.result.wordType,
            phonetic: res.result.phonetic,
            synonyms: res.result.synonyms,
            relWord: res.result.relWord
          }

          this.selectedIndex = -1
          this.showResult = false
        } else {
          uni.showToast({
            title: '获取单词失败',
            icon: 'none'
          })
        }
      } catch (error) {
        uni.hideLoading()
        uni.showToast({
          title: '获取单词失败',
          icon: 'none'
        })
        console.error('获取单词出错:', error)
      }
    },
    playPronunciation() {
      // 创建音频上下文
      const innerAudioContext = uni.createInnerAudioContext()

      // 获取当前单词
      const word = this.currentWord.word

      // 设置音频源（1为美音，2为英音）
      const type = this.isAmericanAccent ? 1 : 2
      innerAudioContext.src = `https://dict.youdao.com/dictvoice?audio=${word}&type=${type}`

      // 监听音频加载完成事件
      innerAudioContext.onCanplay(() => {
        console.log('音频准备就绪')
      })

      // 监听播放错误事件
      innerAudioContext.onError((res) => {
        console.log('播放错误:', res.errMsg)
        uni.showToast({
          title: '音频播放失败',
          icon: 'none'
        })
      })

      // 监听播放完成事件
      innerAudioContext.onEnded(() => {
        console.log('播放结束')
        // 播放完成后销毁实例
        innerAudioContext.destroy()
      })

      // 开始播放
      innerAudioContext.play()

      // 切换口音
      this.isAmericanAccent = !this.isAmericanAccent
    },
    async selectOption(index) {
      this.selectedIndex = index
      this.showResult = true
      const isCorrect = this.currentWord.options[index].isCorrect

      if (isCorrect) {
        this.correctAnswers++
      } else {
        this.lives--
      }

      // 记录当前学习的单词
      this.learnedWords.push({
        wordId: this.currentWord.correctId,
        isCorrect: isCorrect
      })

      // 检查是否完成所有题目
      if (this.currentIndex >= this.totalWords - 1) {
        clearInterval(this.timer)
        // 判断是否达到通过标准（答对8题以上）
        const isSuccess = this.correctAnswers >= 8
        this.sendChallengeResult(isSuccess)
        // 清除本地存储
        uni.removeStorageSync('challenge_remaining_time')
        uni.removeStorageSync('challenge_started')
        
        uni.showToast({
          title: isSuccess ? '挑战成功！' : '挑战失败：正确题数不足',
          icon: isSuccess ? 'success' : 'none'
        })
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
        return
      }

      // 如果生命值耗尽，结束挑战
      if (this.lives <= 0) {
        clearInterval(this.timer)
        this.sendChallengeResult(false)
        // 清除本地存储
        uni.removeStorageSync('challenge_remaining_time')
        uni.removeStorageSync('challenge_started')
        
        uni.showToast({
          title: '挑战失败：生命值耗尽',
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
        return
      }

      // 保存学习记录
      try {
        await api.saveWord({
          isCurrent: isCorrect ? 0 : 1,
          wordId: this.currentWord.correctId,
          wordType: this.currentWord.book,
          model: 1
        })
      } catch (error) {
        console.error('保存单词学习记录失败:', error)
      }

      // 准备要传递的单词数据
      const wordData = {
        word: {
          text: this.currentWord.word,
          meaning: this.currentWord.options.find(opt => opt.isCorrect).meaning,
          correctAnswer: this.currentWord.options.find(opt => opt.isCorrect).meaning,
          phrases: this.currentWord.phrases,
          examples: this.currentWord.examples,
          phonetic: this.currentWord.phonetic,
          synonyms: this.currentWord.synonyms,
          relWord: this.currentWord.relWord
        },
        selectedAnswer: this.currentWord.options[index].meaning
      }

      // 根据回答结果进行跳转
      if (isCorrect) {
        uni.setStorageSync('wordLearningResult', JSON.stringify(wordData))
        uni.navigateTo({
          url: '/pages/word-result/word-result?mode=challenge&from=challenge'
        })
      } else {
        uni.setStorageSync('currentWordData', JSON.stringify(wordData))
        uni.navigateTo({
          url: '/pages/word-wrong/word-wrong?mode=challenge&from=challenge'
        })
      }
      await this.getUserLevel()
    },
    skipWord() {
      // 跳过当前单词，加载下一个
      this.currentIndex++
      if (this.currentIndex >= this.totalWords) {
        // 挑战完成
        uni.showToast({
          title: '挑战完成',
          icon: 'success'
        })

        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      } else {
        this.loadNextWord()
      }
    },
    async sendLearningRecord(learningTime) {
      try {
        // 将学习时间从毫秒转换为秒
        const timeInSeconds = Math.floor(learningTime / 1000)

        // 准备发送的数据
        const learningData = {
          type: 1, // 挑战模式
          learnTime: timeInSeconds, // 学习时间（秒）
        }

        // 发送请求到后端
        const res = await api.recordLearningTime(learningData)

        if (res.code === 200) {
          console.log('学习记录发送成功')
        } else {
          console.error('学习记录发送失败:', res.message)
        }
      } catch (error) {
        console.error('发送学习记录时出错:', error)
      }
    },
    connectWebSocket() {
      if (this.socketTask) {
        console.log("WebSocket 已连接");
        return;
      }

      this.socketTask = uni.connectSocket({
        url: `ws://localhost:8084/websocket/1900221256965083136`, // 替换为你的 WebSocket 服务器地址
        success: () => console.log("WebSocket 连接成功"),
        fail: (err) => console.error("WebSocket 连接失败", err),
      });

      // 监听 WebSocket 连接打开
      this.socketTask.onOpen(() => {
        console.log("WebSocket 连接已打开");
      });

      // 监听收到消息
      this.socketTask.onMessage((res) => {
        if (JSON.parse(res.data).hp){
          this.maxLives = JSON.parse(res.data).hp
        }
        console.log("收到服务器消息:", JSON.parse(res.data).hp);
      });

      // 监听连接关闭
      this.socketTask.onClose(() => {
        console.log("WebSocket 连接已关闭");
        this.socketTask = null; // 清空 socketTask
      });

      // 监听错误
      this.socketTask.onError((err) => {
        console.error("WebSocket 发生错误", err);
      });
    },

    sendMessage(data) {
      if (this.socketTask) {
        this.socketTask.send({
          data: JSON.stringify(data),
          success: () => console.log("消息发送成功"),
          fail: (err) => console.error("消息发送失败", err),
        });
      } else {
        console.error("WebSocket 未连接，无法发送消息");
      }
    },

    closeWebSocket() {
      if (this.socketTask) {
        this.socketTask.close();
        this.socketTask = null;
      }
    },

    async initializeChallenge() {
      try {
        const res = await api.getLevel()
        if (res.code === 200) {
          this.userLevel = Math.min(8, res.result.level)
          
          // 从本地存储获取剩余时间
          const savedTime = uni.getStorageSync('challenge_remaining_time')
          const savedStarted = uni.getStorageSync('challenge_started')
          
          if (savedTime && savedStarted) {
            this.remainingTime = parseInt(savedTime)
            this.challengeStarted = true
          } else {
            // 首次开始挑战
            const reducedTime = (this.userLevel - 1) * this.timePerLevel
            this.remainingTime = this.baseTime - reducedTime
            this.challengeStarted = true
            
            // 保存到本地存储
            uni.setStorageSync('challenge_remaining_time', this.remainingTime)
            uni.setStorageSync('challenge_started', true)
          }
          
          this.startTimer()
        }
      } catch (error) {
        console.error('获取用户等级失败:', error)
      }
    },
    
    startTimer() {
      this.timer = setInterval(() => {
        if (this.remainingTime > 0) {
          this.remainingTime--
          // 更新本地存储的时间
          uni.setStorageSync('challenge_remaining_time', this.remainingTime)
        } else {
          this.handleTimeout()
        }
      }, 1000)
    },

    handleTimeout() {
      clearInterval(this.timer)
      this.sendChallengeResult(false)
      // 清除本地存储
      uni.removeStorageSync('challenge_remaining_time')
      uni.removeStorageSync('challenge_started')
      
      uni.showToast({
        title: '挑战失败：时间到！',
        icon: 'none'
      })
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    },

    formatTime(seconds) {
      const minutes = Math.floor(seconds / 60)
      const remainingSeconds = seconds % 60
      return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
    },

    async sendChallengeResult(isSuccess) {
      try {
        await api.saveWord({
          type: isSuccess ? 2 : 3, // 2表示挑战成功，3表示挑战失败
          wordId: this.currentWord.correctId,
          wordType: this.currentWord.book,
          model: 1 // 挑战模式
        })
      } catch (error) {
        console.error('发送挑战结果失败:', error)
      }
    },
  },
}
</script>

<style lang="scss">
.container {
  min-height: 100vh;
  background-image: linear-gradient(to bottom, #f8e5d7, #a8e6e2);
  padding: 40rpx;
  box-sizing: border-box;
}

.nav-bar {
  display: flex;
  flex-direction: column;
  margin-bottom: 40rpx;

  .left {
    display: flex;
    align-items: center;
    gap: 20rpx;
    margin-bottom: 20rpx;

    .back-icon {
      width: 40rpx;
      height: 40rpx;
    }

    .progress {
      font-size: 32rpx;
      color: #333;
    }
  }
}

.stats {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .lives {
    display: flex;
    gap: 10rpx;

    .heart {
      font-size: 40rpx;

      &.lost {
        opacity: 0.3;
      }
    }
  }

  .xp-score {
    display: flex;
    align-items: center;
    gap: 20rpx;

    .score, .xp {
      background: rgba(255, 255, 255, 0.8);
      padding: 10rpx 20rpx;
      border-radius: 30rpx;
      display: flex;
      align-items: center;

      .score-label, .xp-label {
        font-size: 24rpx;
        color: #666;
        //margin-right: 5rpx;
        width: 50rpx;
      }

      .score-value {
        font-size: 28rpx;
        color: #ff6b21;
        font-weight: bold;
        width: 50rpx;
      }

      .xp-value {
        font-size: 28rpx;
        color: #4CAF50;
        font-weight: bold;
      }
    }
  }
}

.word-section {
  margin-top: 30rpx;
  text-align: center;

  .word {
    font-size: 80rpx;
    font-weight: bold;
    color: #333;
  }

  .phonetic {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 10rpx;
    margin: 30rpx 0;

    .radio {
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: rgba(197, 198, 199, 0.5);
      width: 100rpx;
      border-radius: 10px;

      .region {
        font-size: 24rpx;
      }

      .speaker {
        font-size: 36rpx;
        margin-left: 10rpx;
      }

      .audio-icon {
        width: 25rpx;
        height: 25rpx;
      }
    }

    .symbol {
      font-size: 32rpx;
      color: #666;
    }
  }

  .tip {
    font-size: 28rpx;
    color: #666;
    margin-top: 40rpx;
  }
}

.options {
  margin-top: 60rpx;
  padding: 0 20rpx;

  .definition-item {
    background: rgba(255, 255, 255, 0.8);
    border-radius: 20rpx;
    padding: 30rpx;
    margin-bottom: 20rpx;

    .pos {
      color: #666;
      font-size: 28rpx;
      margin-bottom: 10rpx;
      display: block;
    }

    .meaning {
      color: #333;
      font-size: 32rpx;
    }

    &:active {
      background: rgba(255, 255, 255, 0.6);
    }
  }
}

.bottom-button {
  margin-top: 40rpx;
  background: #333;
  color: white;
  text-align: center;
  padding: 25rpx 0;
  border-radius: 10rpx;
  font-size: 32rpx;
}

.countdown {
  text-align: center;
  margin-top: 20rpx;
  
  .time {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
    background: rgba(255, 255, 255, 0.8);
    padding: 10rpx 30rpx;
    border-radius: 30rpx;
  }
}
</style> 